package book;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl implements BookDao {

	private List<Book> books;
	// 创建文件名的引用
	private String fileName;

	public BookDaoImpl() {
		books = new ArrayList<>();
		fileName = "books.txt";
		readFile();
	}

	// 读文件
	private void readFile() {
		try (FileInputStream fis = new FileInputStream(fileName); 
				ObjectInputStream ois = new ObjectInputStream(fis);) {
			// 判断是否为空
			if (fis != null && ois != null && fis.available() > 10) {
				// 读取集合
				books = (List<Book>) ois.readObject();
			}
		} catch (FileNotFoundException e) {
			System.err.println("books.txt文件不存在");
		} catch (IOException e) {
			System.err.println("books.txt文件读取错误");
		} catch (ClassNotFoundException e) {
			System.err.println("类不存在");
		}
	}

	// 写文件
	private void writeFile() {
		try (FileOutputStream fis = new FileOutputStream(fileName);
				ObjectOutputStream ois = new ObjectOutputStream(fis);) {
			ois.writeObject(books);
			ois.flush();
		} catch (FileNotFoundException e) {
			System.err.println("books.txt文件不存在");
		} catch (IOException e) {
			System.err.println("books.txt文件读取错误");
		}
	}

	@Override
	public boolean insert(Book book) {
		if (books.contains(book)) {
			return false;
		} else {
			books.add(book);
			writeFile();
			return true;
		}
	}

	@Override
	public boolean update(Book book) {
		int index = books.indexOf(book);
		if (index == -1) {
			return false;
		} else {
			books.set(index, book);
			writeFile();
			return true;
		}
	}

	@Override
	public boolean delete(int id) {
		for (Book book : books) {
			if (book.getBookId() == id) {
				books.remove(book);
				writeFile();
				return true;
			}
		}
		return false;
	}

	@Override
	public Book selectById(int id) {
		for (Book book : books) {
			if (book.getBookId() == id) {
				return book;
			}
		}
		return null;
	}

	@Override
	public List<Book> selectAll() {
		List<Book> copy = new ArrayList<>(books);
		return copy;
	}

}
